package com.fansy.rest;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

import com.fansy.service.UploadService;

import edu.emory.mathcs.backport.java.util.Collections;

@Controller
public class RestController {	
	public RestController() {		
	}
	
	@Autowired
	private UploadService uploadService;
	
	
	@RequestMapping(value="/fetch.json",method=RequestMethod.POST)
	public ModelAndView fetchImg(@RequestParam(value="currentPage") int currentPage, @RequestParam(value="pageSize") int pageSize, HttpServletRequest httpServletRequest) {
		//System.out.println(currentPage + " " + pageSize);
		
		List<String> imags = readPictures(currentPage, pageSize, httpServletRequest);
		ModelAndView modleMap = new ModelAndView();
		modleMap.addObject("success",true);
		modleMap.addObject("imags",imags);
		return modleMap;
	}
	
	@SuppressWarnings("unchecked")
	private List<String> readPictures(int currentPage, int pageSize, HttpServletRequest httpServletRequest) {
		List<String> picLst = (List<String>)httpServletRequest.getSession().getAttribute("pic");
		List<String> returnPic = new ArrayList<String>();
		if(picLst==null || picLst.size()==0) {
			picLst = new ArrayList<String>();
			String basePath = httpServletRequest.getSession().getServletContext().getRealPath("/");
			File parentFolder = new File(basePath + "pictures");
			Collection<File> files = (Collection<File>)FileUtils.listFiles(parentFolder, new String[]{"jpg","jpeg","bmp","gif"}, false);
			for(File file:files) {
				picLst.add(file.getName());
			}
			Collections.sort(picLst);
			httpServletRequest.getSession().setAttribute("pic", picLst);			
		}
		
		int totalCount = picLst.size();
		if(totalCount>0) {
			int totalPages = 0;
			if(totalCount%pageSize==0) {
				totalPages = totalCount/pageSize;				
			} else {
				totalPages = totalCount/pageSize +1;
			}
			
			if(currentPage>totalPages) {
				currentPage = currentPage%(totalPages);
				if(currentPage==0) {
					currentPage = totalPages;
				}
			}
			int begin, end;
			if(currentPage!=totalPages) {
				begin = (currentPage-1)*pageSize+1;
				end = currentPage*pageSize;				
			} else {
				begin = (currentPage-1)*pageSize+1;
				end = totalCount;
			}
						
			for(int i=(begin-1);i<end;i++) {
				returnPic.add(picLst.get(i));
			}
		} else {
			return null;
		}
		
		return returnPic;
	}

	private String[] readPictures() {
		return new String[]{"0.jpg", "1.jpg", "2.jpg","3.jpg", "4.jpg", "5.jpg","6.jpg", "7.jpg", "8.jpg","9.jpg","10.jpg","11.jpg", "12.jpg","13.jpg", "14.jpg", "15.jpg","16.jpg", "17.jpg", "18.jpg","19.jpg","20.jpg"};
	}

	@RequestMapping(value="/upload.json",method=RequestMethod.POST)
	public ModelAndView upload(HttpServletRequest httpServletRequest) {
		httpServletRequest.getSession().removeAttribute("pic");
		MappingJacksonJsonView jsonView = new MappingJacksonJsonView();
    	jsonView.setContentType("text/html");
    	ModelAndView modleMap = new ModelAndView(jsonView);
		// Create a factory for disk-based file items
    	DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    	ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    	try {
			@SuppressWarnings("unchecked")
			List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
			for(FileItem fileItemCurrent : listFileItems) {
				if(!fileItemCurrent.isFormField()) {
					byte[] contents = fileItemCurrent.get();
					String name = fileItemCurrent.getName();
					if(name.indexOf("\\")!=-1) {
						name = name.substring(name.lastIndexOf("\\") + 1);
					} else if(name.indexOf("/")!=-1) {
						name = name.substring(name.lastIndexOf("/") + 1);
					}
					System.out.println(name + contents);
					modleMap.addObject("success", true);
					modleMap.addObject("name", name);										
					String path = httpServletRequest.getSession().getServletContext().getRealPath("/");
					String filename = uploadService.uploadFile(contents, path + "pictures/" + name);					
					modleMap.addObject("imageUrl", httpServletRequest.getContextPath() + "/pictures/" + filename);
					break;
				}
			}
		} catch (Exception e) {
			String errorMsg = "Fail to upload picture " + e.getMessage();
			this.handleFailure(modleMap, errorMsg);
		}
    	return modleMap;		
	}
	
    private void handleFailure(ModelAndView modleMap, String errorMessage)
    {
        Map<String, String> errorMap = new HashMap<String, String>();
        errorMap.put("Error", errorMessage);
        
        modleMap.addObject("xmlModelKey", "<error><message>"+errorMessage+"</message></error>");
        modleMap.addObject("Errors", errorMap);
        modleMap.addObject("success", false);
    }

	public UploadService getUploadService() {
		return uploadService;
	}

	public void setUploadService(UploadService uploadService) {
		this.uploadService = uploadService;
	}
	
	public static void main(String args[]) {
		System.out.println(100/100);
		
	}
    
}
